package com.stardata.liangshisq.tcslmon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stardata.liangshisq.tcslmon.entity.*;
import com.stardata.liangshisq.tcslmon.mapper.ArchItemMapper;
import com.stardata.liangshisq.tcslmon.mapper.KcItemfilterDetailMapper;
import com.stardata.liangshisq.tcslmon.mapper.KcItemfilterShopMapper;
import com.stardata.liangshisq.tcslmon.service.SysParameterService;
import com.stardata.liangshisq.tcslmon.util.BeanUtil;
import org.jetbrains.annotations.NotNull;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Samson Shu
 * @email shush@stardata.top
 * @date 2020/12/16 21:45
 */

public class KitchenQueryUtil {
  private static List<Long> kdsClassIds = null;
  private static final String TOKEN = "get_kdsClassIds_token";
  /**
   * 找出当前门店的所有KDS菜品小类id列表
   * @return 当前门店所有的KDS小类ID列表
   */
  @NotNull
  public static List<Long> getKdsClassIds() {
    synchronized (TOKEN) {
       if (kdsClassIds != null) return kdsClassIds;

      SysParameterService parameterService = BeanUtil.getBean(SysParameterService.class);
      KcItemfilterShopMapper kcItemfilterShopMapper = BeanUtil.getBean(KcItemfilterShopMapper.class);
      KcItemfilterDetailMapper kcItemfilterDetailMapper = BeanUtil.getBean(KcItemfilterDetailMapper.class);

      long shopId = Long.parseLong(parameterService.getByCode("shopId"));

      QueryWrapper<KcItemfilterShop> kcItemfilterShopWrapper = new QueryWrapper<>();
      kcItemfilterShopWrapper.eq("shop_id", shopId)
          .eq("delflg", 0);
      List<KcItemfilterShop> shopKdsItemfilters =kcItemfilterShopMapper.selectList(kcItemfilterShopWrapper);
      if (shopKdsItemfilters.size()<1) return  new ArrayList<>();

      List<Long> kcItemfilterIds = new ArrayList<>();
      shopKdsItemfilters.forEach(item -> kcItemfilterIds.add(item.getKcItemfilterId()));

      QueryWrapper<KcItemfilterDetail> kcItemfilterDetailWrapper = new QueryWrapper<>();
      kcItemfilterDetailWrapper.in("itemfilter_id", kcItemfilterIds)
          .eq("delflg", 0);
      List<KcItemfilterDetail> kcItemfilterDetails =
          kcItemfilterDetailMapper.selectList(kcItemfilterDetailWrapper);
      if (kcItemfilterDetails.size()<1) return new ArrayList<>();

      kdsClassIds = new ArrayList<>();
      kcItemfilterDetails.forEach(item -> kdsClassIds.add(item.getDetailId()));

      return kdsClassIds;
    }
  }

  /**
   * 将KcKsc列表进行处理，去掉非后厨菜品记录，并为每个菜品设置ArchItem对象，以及是否临时菜品标记
   * @param kcKscList 待处理的kcKsc列表
   * @param archItemMapper 用于查询ArchItem的Mapper对象
   */
  public static void clearKcKscForNotKitchen(List<KcKsc> kcKscList, ArchItemMapper archItemMapper) {
    List<Long> kdsClassIds = KitchenQueryUtil.getKdsClassIds();
    for (int i = kcKscList.size() - 1; i >= 0; i--) {
      KcKsc kcKsc = kcKscList.get(i);
      ArchItem archItem = archItemMapper.selectById(kcKsc.getItemId());
      kcKsc.setArchItem(archItem);
      if (archItem == null) {
        kcKsc.setIsTempItem(true);
      } else {
        if (!kdsClassIds.contains(archItem.getSmallClassId())) {
          kcKscList.remove(i);
        } else {
          kcKsc.setIsTempItem(archItem.getIsTempItem());
        }
      }
    }
  }

  public static void mergeProductVo4SameBs(List<ProductVo> products) {
    SysParameterService parameterService = BeanUtil.getBean(SysParameterService.class);
    List<Long> needMergeItemIds = parameterService.getListByCode("needMergeItemIds", Long.class);
    if (needMergeItemIds.size()>0) {
      Map<String, ProductVo> mergedItems = new HashMap<>();
      List<ProductVo> productsToRemove = new ArrayList<>();
      for (ProductVo product : products) {
        Long itemId = null;
        try {itemId = Long.parseLong(product.getItemId());}
        catch (NumberFormatException ignore) {}
        Long bsId = product.getBsId();
        if (itemId!=null && needMergeItemIds.contains(itemId)) {
          //将同一个桌位订单下的、指定可以合并的菜品项的记录（且后厨状态相同），合并到第一条记录
          String key = String.format("%d-%d-%d",  bsId, itemId, product.getStatus());
          ProductVo mergedItem = mergedItems.get(key);
          if (mergedItem == null) {
            mergedItems.put(key, product);
          } else {
            BigDecimal newOrigQty = BigDecimal.valueOf(
                mergedItem.getOrigQty().doubleValue() + product.getOrigQty().doubleValue());
            BigDecimal newLastQty = BigDecimal.valueOf(
                mergedItem.getLastQty().doubleValue() + product.getLastQty().doubleValue());

            mergedItem.setOrigQty(newOrigQty);
            mergedItem.setLastQty(newLastQty);
            mergedItem.getKscIds().addAll(product.getKscIds());

            productsToRemove.add(product);
          }
        }
      }
      //将同一个桌位订单下的、指定可以合并的菜品项的记录，除了第一条记录外的都删除
      for (ProductVo product : productsToRemove) {
        products.remove(product);
      }
    }
  }
}
